#pragma once

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

#include "os/path/path.hpp"
#include "os/os.hpp"

namespace glob {
    std::vector<std::string> glob(const std::string& pathname);
    std::vector<std::string> glob(const std::string& pathname, const std::string& root);
}

namespace glob {
    inline bool matches_pattern(const std::string& filename, const std::string& pattern) {
        // 处理简单的通配符情况
        if (pattern == "*") return true;
        
        // 检查文件扩展名
        if (pattern.find("*.") == 0) {
            std::string ext = pattern.substr(1);
            if (filename.size() >= ext.size() && 
                filename.substr(filename.size() - ext.size()) == ext) {
                return true;
            }
            return false;
        }
        
        // 其他简单匹配逻辑（可选）
        // 这里只处理了最常见的 *.ext 情况
        return false;
    }
    
    inline std::vector<std::string> glob_single_directory(const std::string& pattern) {
        std::vector<std::string> result;
        
        // 分离目录和文件名模式
        std::string dirname = os::path::dirname(pattern);
        std::string basename_pattern = os::path::basename(pattern);
        
        // 标准化目录名
        if (dirname == ".") {
            dirname = "";
        }
        
        // 确定搜索目录
        std::string search_dir = dirname.empty() ? "." : dirname;
        
        // 检查目录是否存在
        if (!os::path::exists(search_dir)) {
            std::cerr << "Directory does not exist: " << search_dir << std::endl;
            return result;
        }
        
        // 获取目录中的所有条目
        auto entries = os::listdir(search_dir);
        
        // 匹配条目
        for (const auto& entry : entries) {
            // 跳过目录，只匹配文件
            std::string full_entry = os::path::join(search_dir, entry);
            if (!os::path::isfile(full_entry)) {
                continue;
            }
            
            if (matches_pattern(entry, basename_pattern)) {
                if (dirname.empty()) {
                    result.push_back(entry);
                } else {
                    result.push_back(os::path::join(dirname, entry));
                }
            }
        }
        
        return result;
    }
    
    inline std::vector<std::string> glob(const std::string& pathname) {
        // 如果路径没有通配符，直接检查是否存在
        if (pathname.find('*') == std::string::npos) {
            if (os::path::exists(pathname)) {
                return {pathname};
            }
            return {};
        }
        
        return glob_single_directory(pathname);
    }
    
    inline std::vector<std::string> glob(const std::string& pathname, const std::string& root) {
        std::string full_path = os::path::join(root, pathname);
        return glob(full_path);
    }
}